# Copyright (c) 2022-2023, Arm Limited and Contributors. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

project(lwip-cmsis-port)

add_subdirectory(lwip_sys)

set(CMSIS_PACKS
    "ARM::CMSIS@5.9.0" # Needed for pack description only. No components built from it.
    "lwIP::lwIP@2.2.0"
)

# This is a shim-layer component between lwip and CMSIS Ethernet Driver.
# CMSIS Ethernet Driver is expected to be prowided by cmsis-pack-platform library.
set(CMSIS_PACK_COMPONENTS
    "lwIP::Network&lwIP:Driver:Ethernet&CMSIS Driver@2.2.0"
)

if(CMAKE_C_COMPILER_ID STREQUAL "GNU")
    set(CMSIS_PACK_COMPILER "GCC")
elseif(CMAKE_C_COMPILER_ID STREQUAL "ARMClang")
    set(CMSIS_PACK_COMPILER "AC6")
endif()

if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m0)
    set(CMSIS_PACK_CPU "ARMCM0")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m3)
    set(CMSIS_PACK_CPU "ARMCM3")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m4)
    set(CMSIS_PACK_CPU "ARMCM4")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m7)
    set(CMSIS_PACK_CPU "ARMCM7")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m23)
    set(CMSIS_PACK_CPU "ARMCM23")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m33)
    set(CMSIS_PACK_CPU "ARMCM33")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m55)
    set(CMSIS_PACK_CPU "ARMCM55")
elseif(${CMAKE_SYSTEM_PROCESSOR} STREQUAL cortex-m85)
    set(CMSIS_PACK_CPU "ARMCM85")
else()
    message(FATAL_ERROR "No port found for processor: ${CMAKE_SYSTEM_PROCESSOR}")
endif()

add_cmsis_library(
    cmsis-driver-eth
    ${CMSIS_PACK_CPU}
    ${CMSIS_PACK_COMPILER}
    CMSIS_PACKS
    CMSIS_PACK_COMPONENTS
)

target_link_libraries(cmsis-driver-eth
    PRIVATE
        lwipcore
        lwip-cmsis-sys
        lwipopts
        cmsis-pack-platform
)

# lwipopts library is used to supply configuration for lwIP

add_library(lwipopts INTERFACE)

# IMPORTANT: user applications must provide a "user_lwipopts.h" file which can be an empty
# file or contain lwIP options the user wants to override. This can be done by adding
# an include directory to lwipopts that contains the file.

target_include_directories(lwipopts
    INTERFACE
        cmsis-driver-eth/RTE/Network
)

add_library(lwip-cmsis-port EXCLUDE_FROM_ALL)

target_include_directories(lwip-cmsis-port
    PRIVATE
        include
)

target_sources(lwip-cmsis-port
    PRIVATE
        src/ip_network_api.c
        src/lwip_stack.c
)

target_link_libraries(lwip-cmsis-port
    PRIVATE
        cmsis-driver-eth
        lwipcore
        lwip-cmsis-sys
        iotsdk-ip-network-api
    PUBLIC
        lwipopts
        lwip-cmsis-sys
)

add_library(lwip-cmsis-port-low-input-latency INTERFACE)

target_compile_definitions(lwip-cmsis-port-low-input-latency
    INTERFACE
        IOTSDK_LWIP_LOW_INPUT_LATENCY
        IOTSDK_LWIP_INPUT_TASK_THREAD_PRIORITY=osPriorityRealtime
        IOTSDK_LWIP_TCPIP_THREAD_PRIORITY=osPriorityHigh
)
